import axios from 'axios';
import router from "@/router/index"
import store from "@/store/store";
// 引入地址、端口、一级路由
import {
    address,
    pathApi
} from "@/api/path";
const service = axios.create({
    // 5s未响应自动结束
    timeout: 5000
});
// 请求拦截器
service.interceptors.request.use(
    config => {
        // let token = store.state.login.token;
        // 如果token存在，给请求头部添加token
        let token=localStorage.getItem("token");
        if (token) {
            config.headers['token'] = token;
        }
        // 登录方法拦截 登录采用formData方式提交，变更请求头
        if(config.url===`${address}${pathApi}/login/sumit`){
            config.headers['Content-Type'] = "application/x-www-form-urlencoded";
        }else{
            config.headers['Content-Type'] = "application/json";
        }
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);
// 应答拦截器
service.interceptors.response.use(
    response => {
        if (response.status === 200) {
            return response.data;
        } else {
            Promise.reject();
        }
    },
    error => {
        if (error.response.status === 401) {
            alert("登录超时,请重新登录！");
            router.replace({
                path: '/login',
            });
        }
        return Promise.reject();
    }
);

export default service;